package com.container.core;

import com.container.registration.MyFilterRegistration;
import com.container.registration.MyServletRegistration;
import com.container.util.MimeTypeUtil;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.descriptor.JspConfigDescriptor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

//实现java标准的servletcontext接口，有些没用到的功能省略了
public class MyServletContext implements ServletContext {
    private final Logger log = LoggerFactory.getLogger(getClass());//日志

    private final String contextPath;
    private final ClassLoader classLoader;
    private final String serverInfo;
    private MyUrlPatternMapper urlMapper;
    private volatile boolean initialized;

	private final Map<String, MyServletRegistration> servlets = new HashMap<>();
	private final Map<String, MyFilterRegistration> filters = new HashMap<>();
    private final Map<String, String> urlMappings = new HashMap<>(); //保存url路径与servlet名的映射关系
    private final Hashtable<String, Object> attributes = new Hashtable<>();

    //构造方法，在MyEmbeddedServletContainerFactory中调用
    public MyServletContext(String contextPath, ClassLoader classLoader, String serverInfo) {
        if(contextPath.endsWith("/")){
            contextPath = contextPath.substring(0, contextPath.length() -1);
        }
        this.contextPath = contextPath;
        this.classLoader = classLoader;
        this.serverInfo = serverInfo;
        this.urlMapper = new MyUrlPatternMapper(contextPath);
    }

    //添加一个url-servlet映射关系
	public void addMapping(String url, String name, Servlet servlet) throws ServletException {
        checkNotInitialised();//检查初始化是否已完成
        urlMappings.put(url, checkNotNull(name));
        urlMapper.addServlet(url, servlet, name);
    }
	
	//暂不需要filter
	public void addFilterMapping(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String url) {
        checkNotInitialised();
    }

    //以下为添加、创建servlet相关方法
    @Override
    public <T extends Servlet> T createServlet(Class<T> c) throws ServletException {
        try {
            return c.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
           log(e, "Throwing exception when creating instance of " + c.getName());
        }
        return null;
    }

    @Override
    public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) {
        return addServlet(servletName, servletClass.getName());
    }

    @Override
    public ServletRegistration.Dynamic addServlet(String servletName, String className) {
        return addServlet(servletName, className, null);
    }

    @Override
    public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
        return addServlet(servletName, servlet.getClass().getName(), servlet);
    }

    private ServletRegistration.Dynamic addServlet(String servletName, String className, Servlet servlet) {
        MyServletRegistration sr = new MyServletRegistration(this, servletName, className, servlet);
        servlets.put(servletName, sr);
        return sr;
    }

    @Override
    public ServletRegistration getServletRegistration(String servletName) {
        return null;
    }

    @Override
    public Map<String, ? extends ServletRegistration> getServletRegistrations() {
        return null;
    }

    //以下为添加、创建filter相关方法
    @Override
    public <T extends Filter> T createFilter(Class<T> c) throws ServletException {
        try {
            return c.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
        	log(e, "Throwing exception when creating instance of " + c.getName());
        }
        return null;
    }

    @Override
    public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
        return addFilter(filterName, filterClass.getName());
    }

    @Override
    public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, String className) {
        return addFilter(filterName, className, null);
    }

    @Override
    public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
        return addFilter(filterName, filter.getClass().getName(), filter);
    }

    private javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, String className, Filter filter) {
        MyFilterRegistration fr = new MyFilterRegistration(this, filterName, className, filter);
        filters.put(filterName, fr);
        return fr;
    }

    @Override
    public javax.servlet.FilterRegistration getFilterRegistration(String filterName) {
        return filters.get(filterName);
    }

    @Override
    public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
        return ImmutableMap.copyOf(filters);
    }

    //根据路径分发请求
    @Override
    public RequestDispatcher getRequestDispatcher(String url) {
        String servletName = urlMapper.getServletName(url);
        Servlet servlet = null;

        try {
            servlet = null == servletName ? null : servlets.get(servletName).getServlet();
            if (servlet == null) {
                return null;
            }
            
            List<Filter> allFilters = new ArrayList<>();
            for (MyFilterRegistration r : this.filters.values()) {
                allFilters.add(r.getFilter());
            }
            FilterChain filterChain = new MyFilterChain(servlet, allFilters);
            return new NettyRequestDispatcher(this, filterChain);
        } catch (ServletException e) {
            log(e, "Throwing exception when getting Filter from MyFilterRegistration of path " + url);
            return null;
        }
    }

    @Override
    public RequestDispatcher getNamedDispatcher(String name) {
        return null;
    }

    @Override
    public Servlet getServlet(String name) throws ServletException {
        return servlets.get(name).getServlet();
    }

    @Override
    public Enumeration<Servlet> getServlets() {
        return Collections.emptyEnumeration();
    }

    @Override
    public Enumeration<String> getServletNames() {
        return Collections.emptyEnumeration();
    }

    @Override
    public String getContextPath() {
        return contextPath;
    }

	@Override
    public ServletContext getContext(String url) {
        return this;
    }

    //加载资源
    @Override
    public URL getResource(String path) throws MalformedURLException {
        if (!path.startsWith("/")) {
            throw new MalformedURLException("Path '" + path + "' does not start with '/'");
        }

        URL url = new URL(getClassLoader().getResource(""), path.substring(1));

        try {
            url.openStream();
        } catch(FileNotFoundException e) {
            url = new URL(getClassLoader().getResource(""), "static/" + path.substring(1));
            try {
                url.openStream();
            } catch (IOException ioe) {
                log(ioe, "Throwing exception when getting InputStream of " + path + " in /static");
                url = null;
            }
        } catch (Throwable t) {
            log("Throwing exception when getting InputStream of " + path + " in /", t);
            url = null;
        }
        return url;
    }

    @Override
    public Set<String> getResourcePaths(String path) {
        Set<String> paths = new HashSet<>();
        if (!path.endsWith("/")) {
            path += "/";
        }
        String basePath = getRealPath(path);
        if (basePath == null) {
            return paths;
        }

        File baseDir = new File(basePath);
        if (!baseDir.exists() || !baseDir.isDirectory()) {
            return paths;
        }

        String files[] = baseDir.list();
        if (files == null) {
            return paths;
        }

        for (String filename : files) {
            File temp = new File(basePath + File.separator + filename);
            if (temp.isFile()) {
                paths.add(path + filename);
            } else if (temp.isDirectory()) {
                paths.add(path + filename + "/");
            }
        }
        return paths;
    }

    @Override
    public InputStream getResourceAsStream(String path) {
        try {
            return getResource(path).openStream();
        } catch (IOException e) {
            log(e, e.getMessage());
            return null;
        }
    }

    @Override
    public String getRealPath(String path) {
        if (!path.startsWith("/")) return null;
        try {
            File f = new File(getResource(path).toURI());
            return f.getAbsolutePath();
        } catch (Throwable t) {
            log("Throwing exception when getting real path of " + path, t);
            return null;
        }
    }

    @Override
    public Object getAttribute(String name) {
        return attributes.get(name);
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return attributes.keys();
    }

    @Override
    public void setAttribute(String name, Object object) {
        attributes.put(name, object);
    }

    @Override
    public void removeAttribute(String name) {
        attributes.remove(name);
    }

    @Override
    public String getMimeType(String file) {
        return MimeTypeUtil.getMimeTypeByFileName(file);
    }

    @Override
    public String getServerInfo() {
        return serverInfo;
    }

    @Override
    public String getInitParameter(String name) {
        return null;
    }

    @Override
    public Enumeration<String> getInitParameterNames() {
        return Collections.emptyEnumeration();
    }

    @Override
    public boolean setInitParameter(String name, String value) {
        return false;
    }

    @Override
    public String getServletContextName() {
        return getContextPath().toUpperCase(Locale.ENGLISH);
    }

    @Override
    public int getMinorVersion() {
        return 0;
    }

    @Override
    public int getEffectiveMinorVersion() {
        return 0;
    }

    @Override
    public int getMajorVersion() {
        return 3;
    }

    @Override
    public int getEffectiveMajorVersion() {
        return 3;
    }

    void setInitialized(boolean initialized) {
        this.initialized = initialized;
    }

    private boolean isInitialized() {
        return initialized;
    }

    private void checkNotInitialised() {
        checkState(!isInitialized(), "上下文初始化还未完成！");
    }

    @Override
    public void log(String msg) {
        log.info(msg);
    }

    @Override
    public void log(Exception exception, String msg) {
        log.error(msg, exception);
    }

    @Override
    public void log(String message, Throwable throwable) {
        log.error(message, throwable);
    }

    //以下是session、cookie、listener相关方法，项目用不到，先留空
    @Override
    public SessionCookieConfig getSessionCookieConfig() {
        return null;
    }

    @Override
    public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes) throws IllegalStateException, IllegalArgumentException {}

    @Override
    public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
        return null;
    }

    @Override
    public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
        return null;
    }

    @Override
    public void addListener(String className) {}

    @Override
    public <T extends EventListener> void addListener(T t) {}

    @Override
    public void addListener(Class<? extends EventListener> listenerClass) {}

    @Override
    public <T extends EventListener> T createListener(Class<T> c) throws ServletException {
        return null;
    }

    @Override
    public void declareRoles(String... roleNames) {}

    @Override
    public String getVirtualServerName() {
        return null;
    }

    @Override
    public ClassLoader getClassLoader() {
        return classLoader;
    }

    @Override
    public JspConfigDescriptor getJspConfigDescriptor() {
        return null;
    }

}